<template>
  <t-enhanced-table
    v-model:expanded-tree-nodes="expandedTreeNodes"
    :columns="centeredColumns"
    :data="data"
    :row-key="props.rowKey"
    :bordered="tableConfig.bordered"
    hover
    :loading="loading"
    :pagination="havePagination"
    resizable
    :size="tableConfig.size"
    :stripe="tableConfig.stripe"
    :default-display-columns="columnControllerConfig[props.columnControllerKey]"
    :column-controller="{ hideTriggerButton: !props.columnControllerKey, placement: 'bottom-right' }"
    :foot-data="props.footData"
    @page-change="handlePageChange"
    @display-columns-change="handleDisplayColumnsChange"
  >
    <template v-for="slotName in Object.keys(slots)" #[slotName]="slotParams">
      <slot :name="slotName" v-bind="slotParams" />
    </template>
    <template #columnControllerTopContent>
      <div class="columnControllerTopContent">
        <p class="t-table__column-controller-desc top-title">
          自定义表格配置
          <t-button class="reset" theme="default" size="small" @click="handleResetTableConfig">重置</t-button>
        </p>
        <t-row class="config" :gutter="[20, 20]">
          <t-col :span="12">
            表格尺寸：
            <t-radio-group
              v-model:value="tableConfig.size"
              :options="[
                { label: '小', value: 'small' },
                { label: '中', value: 'medium' },
                { label: '大', value: 'large' },
              ]"
            />
          </t-col>
          <t-col :span="6"> 是否显示表格边框：<t-switch v-model:value="tableConfig.bordered" /> </t-col>
          <t-col :span="6"> 是否显示斑马纹：<t-switch v-model:value="tableConfig.stripe" /> </t-col>
        </t-row>
      </div>
      <t-divider />
    </template>
  </t-enhanced-table>
</template>

<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core';
import { CheckboxGroupValue, MessagePlugin, PageInfo, SizeEnum, TableCol } from 'tdesign-vue-next';
import { computed, PropType, reactive, ref, useSlots } from 'vue';

const props = defineProps({
  columns: {
    type: Array as PropType<TableCol[]>,
    required: true,
  },
  rowKey: {
    type: String,
    required: true,
  },
  api: {
    type: Function as PropType<(params: { [key: string]: any }) => Promise<any>>,
    required: true,
  },
  onBeforeSetData: {
    type: Function as PropType<(data: any) => any>,
  },
  columnControllerKey: {
    type: String,
  },
  fixedPageSize: {
    type: Boolean,
    default: false, // 默认不固定 pageSize
  },
  footData: {
    type: Array as PropType<any[]>, // 接收父组件传递的表尾数据
    default: [],
  },
});
const emits = defineEmits(['requestSuccess']);
const slots: Record<string, any> = useSlots();
const expandedTreeNodes = ref([]);
const columnControllerConfig = useLocalStorage<Record<string, CheckboxGroupValue>>('column-controller-config', {});
const data = ref([]);
const loading = ref(false);
const initParams = ref(null);
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});
const handleRefreshTable = () => {
  data.value = [];
  loading.value = true;
  const params = {
    ...initParams.value,
    pageSize: pagination.pageSize,
  };
  if (!props.fixedPageSize) {
    params.pageNo = pagination.current; // 如果不是固定 pageSize，则传递 pageNo
  }
  props
    .api(params)
    .then((d) => {
      if (props.onBeforeSetData && typeof props.onBeforeSetData === 'function') {
        d = props.onBeforeSetData(d) || d;
      }
      if (d.list) {
        data.value = d.list;
        pagination.total = d.total;
      } else {
        data.value = d;
        pagination.total = data.value.length;
      }
      emits('requestSuccess', { params, data: data.value });
    })
    .catch(({ message }) => {
      pagination.total = 0;
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleInitTable = (params: Record<string, any>) => {
  initParams.value = params;
  data.value = [];
  pagination.current = 1;
  pagination.pageSize = props.fixedPageSize ? -1 : params.pageSize || 20;
  pagination.total = 0;
  handleRefreshTable();
};
const handlePageChange = (pageInfo: PageInfo) => {
  pagination.current = pageInfo.current;
  pagination.pageSize = pageInfo.pageSize;
  handleRefreshTable();
};
const handleDisplayColumnsChange = (value: CheckboxGroupValue) => {
  if (props.columnControllerKey) columnControllerConfig.value[props.columnControllerKey] = value;
};
const defaultTableConfig = {
  size: 'small' as SizeEnum,
  bordered: true,
  stripe: true,
};
const tableConfig = useLocalStorage('table-config', defaultTableConfig);
const handleResetTableConfig = () => {
  Object.keys(defaultTableConfig).forEach((key) => {
    (tableConfig.value as any)[key] = (defaultTableConfig as any)[key];
  });
};
const havePagination = computed(() => {
  const { fixedPageSize } = props;
  if(fixedPageSize) return null
  if(!fixedPageSize) return pagination
});
defineExpose({
  initTable: handleInitTable,
  refreshTable: handleRefreshTable,
  data
});
const centeredColumns = computed(() => {
  return props.columns.map(column => ({
    ...column,
    align: column.align || 'center'  // 如果列已经有align设置则保留，否则设为center
  }));
});
</script>

<style lang="less" scoped>
.columnControllerTopContent {
  overflow: hidden;

  .top-title {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .reset {
      margin-left: 10px;
    }
  }

  .config {
    color: var(--td-text-color-primary);
    font: var(--td-font-body-medium);
  }
}
:deep(.t-table__footer) {
  td {
    text-align: center !important;
  }
}
</style>
